<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

// Montrer les erreurs
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

// includes
include_once '../model/config.php';
include_once 'UtilisateurManager.php';

require_once realpath(dirname(__FILE__) . '/../libs/Google/base.php');
require_once realpath(dirname(__FILE__) . '/../libs/Google/autoload.php');

//variables 
$page_accueil = "../view/accueil.php";
$user = "bill";

session_start();

 $client_id = '795189882707-bo8nandjm4mb37aj34sgslelnvqc2cn5.apps.googleusercontent.com';
 $client_secret = '7FMCK3DAfD-SNzuvztzS7cEP';
 $redirect_uri = 'http://www.fixnfax.com/gestiontache/'.$user.'/controller/google.php';

 $client = new Google_Client();
 $client->setClientId($client_id);
 $client->setClientSecret($client_secret);
 $client->setRedirectUri($redirect_uri);
 $client->setScopes('email');

if (isset($_REQUEST['logout'])) {
  unset($_SESSION['access_token']);
}

if (isset($_GET['code'])) {
  $client->authenticate($_GET['code']);
  $_SESSION['access_token'] = $client->getAccessToken();
  $redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
  header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}

if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
  $client->setAccessToken($_SESSION['access_token']);
} else {
  $authUrl = $client->createAuthUrl();
  header('Location: ' . $authUrl);
}

if ($client->getAccessToken()) {
  $_SESSION['access_token'] = $client->getAccessToken();
  $auth2 = new Google_Service_Oauth2($client);
  $manager = new UtilisateurManager($bdd);
  $manager->createUserGoogle($auth2->userinfo_v2_me->get());
       
  //mise en session
  $_SESSION["id"] = $bdd->lastInsertId();
  $_SESSION["photo"] = $auth2->userinfo_v2_me->get()->getPicture();
  $_SESSION['prenom'] = $auth2->userinfo_v2_me->get()->getGivenName();
  
  header("Location:".$page_accueil);
  
}

